﻿//3.24优化图纸排序


using Autodesk.AutoCAD.ApplicationServices;
using Autodesk.AutoCAD.DatabaseServices;
using Autodesk.AutoCAD.EditorInput;
using Autodesk.AutoCAD.Runtime;
using System;
using System.Collections.Generic;
using System.Linq;



namespace Plot08
{
    /// <summary>
    /// 空间标识符
    /// </summary>
    internal enum SpaceId
    {
        ModelSpace,

        PaperSpace

    }

    /// <summary>
    /// 用于操作实际打印的类
    /// </summary>
    public class PlotWin
    {
        static string sAssemblyPath = System.Reflection.Assembly.GetExecutingAssembly().Location;

        static string xmlFilePath = "";

        static string dwgFilePath = "";

        //用于初始化Tk.xml文件的路径及页面设置记录文件的路径

        static PlotWin()
        {
            sAssemblyPath = System.Reflection.Assembly.GetExecutingAssembly().Location;

            string shortName = System.IO.Path.GetFileName(sAssemblyPath);

            xmlFilePath = "";

            xmlFilePath = sAssemblyPath.Replace(shortName, "Tk.xml");

            dwgFilePath = sAssemblyPath.Replace(shortName, "DeaufltPlotSetings.dwg");

        }

        #region 直接打印命令区，用于单个文档打印

        /// <summary>
        /// 用于当前布局（模型或图纸空间中都某个布局）内的框选打印，需要有对应的当前页面设置
        /// </summary>
        [CommandMethod("mp")]
        public static void Any_PlotBySelect()
        {

            Document acDoc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;

            Database acDb = acDoc.Database;

            Editor acEd = acDoc.Editor;

            object o = Autodesk.AutoCAD.ApplicationServices.Application.GetSystemVariable("measurement");

            int svShort = Convert.ToInt16(o);

            if (svShort == 0)
            {

                acEd.WriteMessage("本程序默认使用公制单位进行打印，本图为英制图纸，将临时调整为公制进行打印，打印后恢复为英制");

                Autodesk.AutoCAD.ApplicationServices.Application.SetSystemVariable("measurement", 1);

            }

            bool hasPlotSeting = false;

            string plotSetName = string.Empty;

            string layoutName = string.Empty;

            //判断当前空间是否有当前的页面设置

            hasPlotSeting = LayoutTool.HasPlotSeting(acDoc, out plotSetName);

            #region 设置图框块的名字blockNames

            List<string> blockNames = new List<string>();

            blockNames.Clear();

            if (System.IO.File.Exists(xmlFilePath))
            {

                XmlTool Tool = new XmlTool(xmlFilePath);

                foreach (var item in Tool.Get_TkNameInfo())
                {
                    blockNames.Add(item);
                }

            }
            else
            {
                Application.ShowAlertDialog("没有找到图框块名称记录文件Tk.xml,程序无法运行");

                return;

            }

            #endregion

            if (!hasPlotSeting)
            {
                Autodesk.AutoCAD.ApplicationServices.Application.ShowAlertDialog("本空间未设置当前的页面设置，请设置后再运行本程序");

                return;
            }

            List<BlockReference> blocks = LayoutTool.Get_tk_BlocksBySelect(blockNames);

            if (blocks == null)
            {
                Autodesk.AutoCAD.ApplicationServices.Application.ShowAlertDialog("没有选择到能打印的图框块，请用命令< +tk >将要打印的图框块名称加入Tk.xml中");
                return;

            }

            //按照图框块的页码信息排序

            List<BlockReference> tks = new List<BlockReference>();

            try
            {

                tks = GetGroupedAndOrderedTks(blocks);

            }
            catch (System.Exception e)
            {

                tks = blocks.OrderByDescending(tk => tk.Position.Y).ThenBy(tk => tk.Position.X).ToList<BlockReference>();

            }

            for (int i = 0; i < tks.Count; i++)
            {

                //Extents2d window = LayoutTool.GetBlockExtent2d(tks[i]);

                //Application.ShowAlertDialog(tks[i].Name);

                string name = string.Empty;

                name = layoutName + i;

                string shortName = System.IO.Path.GetFileNameWithoutExtension(acDoc.Name) + "-";

                name = System.IO.Path.Combine(System.IO.Path.GetDirectoryName(acDoc.Name), shortName + name);

                //bool bb = LayoutTool.PlotWindowByCurPlotSetting(window, name);

                bool bb = LayoutTool.PlotWindowByCurPlotSetting(tks[i], name);




            }

            Autodesk.AutoCAD.ApplicationServices.Application.SetSystemVariable("measurement", o);


        }

        /// <summary>
        /// 用于当前布局（模型或图纸空间中都某个布局）内的框选打印，使用指定的页面设置
        /// </summary>
        [CommandMethod("mpa")]
        public static void Any_Plot()
        {

            Document acDoc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;

            Database acDb = acDoc.Database;

            Editor acEd = acDoc.Editor;

            #region 设置打印单位     

            object o = Autodesk.AutoCAD.ApplicationServices.Application.GetSystemVariable("measurement");

            int svShort = Convert.ToInt16(o);

            if (svShort == 0)
            {

                acEd.WriteMessage("本程序默认使用公制单位进行打印，本图为英制图纸，将临时调整为公制进行打印，打印后恢复为英制");

                Autodesk.AutoCAD.ApplicationServices.Application.SetSystemVariable("measurement", 1);

            }

            #endregion

            #region 获取当前布局的BlockTableRecordId，用于后面关联页面设置，同时设置isModel的值，为模型空间则设置为True，否则设置为False；

            ObjectId curLayoutId = ObjectId.Null;

            bool isModel = true;

            //获取当前空间的BlockTableRecordId，同时设置isModel的值，为模型空间则设置为True，否则设置为False；

            curLayoutId = LayoutTool.GetCurSpaceObjectId(out isModel);

            #endregion

            #region 获取指定路径图纸中的与当前空间匹配的页面设置名称，导入指定名称为aPlotSetingsName的页面设置

            List<string> plotSetingsNames = new List<string>();

            List<string> plotInfoSInPlotSetings = new List<string>();

            #region 获取指定路径图纸中的与当前空间匹配的页面设置名称，同时输出每个匹配页面布置所对应的设置信息

            plotSetingsNames = LayoutTool.GetPlotSetingsNames(dwgFilePath, isModel, out plotInfoSInPlotSetings);

            if (plotSetingsNames.Count == 0)
            {

                acEd.WriteMessage("\n没有适用于当前空间的默认页面设置，请使用<svset>命令设置默认页面布局后重试");

                return;

            }

            string aPlotSetingsName = string.Empty;

            //当只有一个的时候，在命令行输出主要页面设置信息

            //当有多个的时候，显示多个页面设置名称，及主要页面设置信息

            if (plotSetingsNames.Count == 1)
            {
                aPlotSetingsName = plotSetingsNames[0];

            }
            else if (plotSetingsNames.Count > 1)
            {

                acEd.WriteMessage("\n当前空间有以下可用的页面设置：\n");

                for (int i = 0; i < plotSetingsNames.Count; i++)
                {

                    acEd.WriteMessage(plotInfoSInPlotSetings[i] + "\n");

                }

            GetPageSetup:

                PromptIntegerOptions prompt_I = new PromptIntegerOptions("");

                prompt_I.AllowNone = true;

                prompt_I.AllowNegative = false;

                prompt_I.DefaultValue = 1;

                prompt_I.Message = "请输入需要使用的页面设置" + "[1-" + (plotSetingsNames.Count).ToString() + "]";

                PromptIntegerResult res_I;

                res_I = acEd.GetInteger(prompt_I);

                if (res_I.Status != PromptStatus.OK)
                {

                    acEd.WriteMessage("\n没有输入有效的页面设置选项，将放弃打印");

                    return;

                }

                if (res_I.Value >= 1 && res_I.Value <= plotSetingsNames.Count)
                {
                    aPlotSetingsName = plotSetingsNames[res_I.Value - 1];


                }
                else
                {
                    goto GetPageSetup;

                }

            }

            #endregion

            bool getInPlotSetings = false;

            if (aPlotSetingsName == string.Empty)
            {
                return;

            }

            getInPlotSetings = LayoutTool.GetInAtPlotSetings(dwgFilePath, aPlotSetingsName, isModel);

            //如果导入不成功，说明相关原因

            if (getInPlotSetings == false)
            {

                acEd.WriteMessage("没有找到所需的页面设置名称,程序放弃打印");

                return;
            }

            #endregion

            //导入页面设置成功,关联打印设置

            if ( LayoutTool.AssignPage_SetupToLayout(curLayoutId, aPlotSetingsName)==false)
            {
                //Application.ShowAlertDialog("关联页面设置到布局失败，程序退出");

                acEd.WriteMessage("\n关联页面设置到布局失败，程序退出,建议设置好页面设置后使用mp命令进行打印");

                return;
            }

            //关联好当前布局与页面设置后，采用打印当前布局的方法，打印对应的图纸。

            Any_PlotBySelect();

            Autodesk.AutoCAD.ApplicationServices.Application.SetSystemVariable("measurement", o);


        }

        /// <summary>
        /// 用于图纸空间的逐个打印，可打印某布局内的多个图框
        /// </summary>
        [CommandMethod("lpa", CommandFlags.NoTileMode)]
        public static void Layout_Plot()
        {

            Document acDoc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;

            Database acDb = acDoc.Database;

            Editor acEd = acDoc.Editor;

            object o = Autodesk.AutoCAD.ApplicationServices.Application.GetSystemVariable("measurement");

            int svShort = Convert.ToInt16(o);

            if (svShort == 0)
            {
                acEd.WriteMessage("本程序默认使用公制单位进行打印，本图为英制图纸，将临时调整为公制进行打印，打印后恢复为英制");

                Autodesk.AutoCAD.ApplicationServices.Application.SetSystemVariable("measurement", 1);

            }

            bool hasPlotSeting = false;

            string dev_name = string.Empty;

            string med_name = string.Empty;

            string style_name = string.Empty;

            #region 读入TK.xm文件中的记录的图框块名称到blockNames

            List<string> blockNames = new List<string>();

            if (System.IO.File.Exists(xmlFilePath))
            {

                XmlTool Tool = new XmlTool(xmlFilePath);

                foreach (var item in Tool.Get_TkNameInfo())
                {

                    blockNames.Add(item);

                }

            }
            else
            {

                Application.ShowAlertDialog("没有找到图框块名称记录文件Tk.xml,程序无法运行");

                return;

            }

            #endregion

            List<ObjectId> layoutIds = new List<ObjectId>();

            List<Layout> layouts = new List<Layout>();

            string plotSetName = string.Empty;

            hasPlotSeting = LayoutTool.HasPlotSeting(acDoc, out plotSetName);

            if (hasPlotSeting == false)
            {

                Autodesk.AutoCAD.ApplicationServices.Application.SetSystemVariable("measurement", o);

                Application.ShowAlertDialog("本命令通过套用本布局当前页面设置打印所有布局，请设置好本布局当前页面设置后重试打印");

                return;

            }

            layoutIds.Clear();

            using (Transaction acTrans = acDb.TransactionManager.StartTransaction())
            {
                DBDictionary LayoutDB = acTrans.GetObject(acDb.LayoutDictionaryId, OpenMode.ForRead) as DBDictionary;

                //acDoc.Editor.WriteMessage("\nLayouts:");

                // Step through and list each named layout and Model
                foreach (DBDictionaryEntry item in LayoutDB)
                {
                    //acDoc.Editor.WriteMessage("\n  " + item.Key);

                    if (item.Key.ToString().ToUpper().Contains("MODEL") == false)
                    {
                      

                        if (LayoutTool.AssignPage_SetupToLayout(item.Value, plotSetName) == false)
                        {
                            //Application.ShowAlertDialog(item.Key.ToString()+"关联页面设置到布局失败，跳过打印" );

                            acEd.WriteMessage("\n"+item.Key.ToString() + "关联页面设置到布局失败，跳过打印");

                            continue;
                        }
                        else
                        {
                            layoutIds.Add(item.Value);
                        }

                        
                    }

                }

                acTrans.Commit();
            }

            //List<string> layoutNames = LayotTool.Get_Layouts(acDoc);


            using (Transaction acTrans = acDb.TransactionManager.StartTransaction())
            {
                DBDictionary LayoutDB = acTrans.GetObject(acDb.LayoutDictionaryId, OpenMode.ForRead) as DBDictionary;

                foreach (ObjectId oid in layoutIds)
                {
                    Layout layout = acTrans.GetObject(oid, OpenMode.ForRead) as Layout;

                    layouts.Add(layout);

                }
                List<Layout> layoutS = new List<Layout>();

                layoutS = layouts.OrderBy(layout => layout.TabOrder).ToList<Layout>();

                foreach (Layout layout_cur in layoutS)
                {
                    BlockTableRecord btr = acTrans.GetObject(layout_cur.BlockTableRecordId, OpenMode.ForRead) as BlockTableRecord;

                    LayoutManager lm = LayoutManager.Current;

                    lm.CurrentLayout = layout_cur.LayoutName;

                    DBDictionary acPlSet = acTrans.GetObject(acDb.PlotSettingsDictionaryId, OpenMode.ForRead) as DBDictionary;

                    PlotSettings plSet = null;

                    // Check to see if the page setup exists
                    if (acPlSet.Contains(plotSetName) == true)
                    {

                        plSet = acPlSet.GetAt(plotSetName).GetObject(OpenMode.ForRead) as PlotSettings;

                    }

                    //List<ObjectId> blockIds = LayoutTool.Get_tk_BlocksIds(blockNames);

                    List<BlockReference> blocks = LayoutTool.Get_tk_BlocksAuto(blockNames, "PAPER");

                    List<BlockReference> blocksInLayout = new List<BlockReference>();

                    blocksInLayout.Clear();

                    foreach (var block in blocks)
                    {
                        if (block.OwnerId == layout_cur.BlockTableRecordId)
                        {
                            blocksInLayout.Add(block);

                        }
                    }
                    //这里还可以加一个图框块按照坐标排序的功能

                    //按照Z形排列打印图纸

                    List<BlockReference> tks = new List<BlockReference>();

                    try
                    {

                        tks = GetGroupedAndOrderedTks(blocksInLayout);

                    }
                    catch (System.Exception)
                    {


                        tks = blocksInLayout.OrderByDescending(tk => tk.Position.Y).ThenBy(tk => tk.Position.X).ToList<BlockReference>();

                        //						throw;
                    }


                    int i = 0;

                    foreach (var block in tks)
                    {
                        Extents2d window = LayoutTool.GetBlockExtent2d(block);

                        string name = string.Empty;

                        if (blocksInLayout.Count > 1)
                        {
                            name = layout_cur.LayoutName + "--" + i;
                        }
                        else
                        {
                            name = layout_cur.LayoutName;
                        }

                        string shortName = System.IO.Path.GetFileNameWithoutExtension(acDoc.Name) + "-";

                        name = System.IO.Path.Combine(System.IO.Path.GetDirectoryName(acDoc.Name), shortName + name);

                        if (plSet != null)
                        {

                            //bool bb = LayoutTool.PlotWindowByCurPlotSetting(window, name);

                            bool bb = LayoutTool.PlotWindowByCurPlotSetting(block, name);

                        }
                        i++;
                    }

                }

                acTrans.Abort();
            }

            Autodesk.AutoCAD.ApplicationServices.Application.SetSystemVariable("measurement", o);
        }


        /// <summary>
        /// 用于当前空间的图纸，使用默认打印设置，调用的是AnyPlot_Auto
        /// </summary>
        [CommandMethod("mpaa")]
        public static void Any_Plot_ALL()
        {

            Document acDoc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;

            Database acDb = acDoc.Database;

            Editor acEd = acDoc.Editor;

            #region 设置打印单位

            object o = Autodesk.AutoCAD.ApplicationServices.Application.GetSystemVariable("measurement");

            int svShort = Convert.ToInt16(o);

            if (svShort == 0)
            {

                acEd.WriteMessage("本程序默认使用公制单位进行打印，本图为英制图纸，将临时调整为公制进行打印，打印后恢复为英制");

                Autodesk.AutoCAD.ApplicationServices.Application.SetSystemVariable("measurement", 1);

            }

            #endregion


            #region 获取当前布局的BlockTableRecordId，用于后面关联页面设置，同时设置isModel的值，为模型空间则设置为True，否则设置为False；

            ObjectId curLayoutId = ObjectId.Null;

            bool isModel = true;

            //获取当前空间的BlockTableRecordId，同时设置isModel的值，为模型空间则设置为True，否则设置为False；

            curLayoutId = LayoutTool.GetCurSpaceObjectId(out isModel);

            #endregion

            #region 获取指定路径图纸中的与当前空间匹配的页面设置名称，导入指定名称为aPlotSetingsName的页面设置

            List<string> plotSetingsNames = new List<string>();

            List<string> plotInfoSInPlotSetings = new List<string>();

            //获取指定路径图纸中的与当前空间匹配的页面设置名称，同时输出每个匹配页面布置所对应的设置信息

            plotSetingsNames = LayoutTool.GetPlotSetingsNames(dwgFilePath, isModel, out plotInfoSInPlotSetings);

            if (plotSetingsNames.Count == 0)
            {

                acEd.WriteMessage("\n没有适用于当前空间的默认页面设置，请使用<svset>命令设置默认页面布局后重试");

                return;

            }

            string aPlotSetingsName = string.Empty;

            //当只有一个的时候，在命令行输出主要页面设置信息

            //当有多个的时候，显示多个页面设置名称，及主要页面设置信息

            if (plotSetingsNames.Count == 1)
            {
                aPlotSetingsName = plotSetingsNames[0];

            }
            else if (plotSetingsNames.Count > 1)
            {

                acEd.WriteMessage("\n当前空间有以下可用的页面设置：\n");

                for (int i = 0; i < plotSetingsNames.Count; i++)
                {

                    acEd.WriteMessage(plotInfoSInPlotSetings[i] + "\n");

                }

            GetPageSetup:

                PromptIntegerOptions prompt_I = new PromptIntegerOptions("");

                prompt_I.AllowNone = true;

                prompt_I.AllowNegative = false;

                prompt_I.DefaultValue = 1;

                prompt_I.Message = "请输入需要使用的页面设置" + "[1-" + (plotSetingsNames.Count).ToString() + "]";

                PromptIntegerResult res_I;

                res_I = acEd.GetInteger(prompt_I);

                if (res_I.Status != PromptStatus.OK)
                {

                    acEd.WriteMessage("\n没有输入有效的页面设置选项，将放弃打印");

                    return;

                }

                if (res_I.Value >= 1 && res_I.Value <= plotSetingsNames.Count)
                {

                    aPlotSetingsName = plotSetingsNames[res_I.Value - 1];


                }
                else
                {
                    goto GetPageSetup;

                }

            }


            bool getInPlotSetings = false;

            if (aPlotSetingsName == string.Empty)
            {
                return;

            }

            getInPlotSetings = LayoutTool.GetInAtPlotSetings(dwgFilePath, aPlotSetingsName, isModel);

            //如果导入不成功，说明相关原因

            if (getInPlotSetings == false)
            {
                acEd.WriteMessage("没有找到所需的页面设置名称,程序放弃打印");

                return;
            }

            #endregion


            //导入页面设置成功,关联打印设置

            if ( LayoutTool.AssignPage_SetupToLayout(curLayoutId, aPlotSetingsName)==false)
            {
                //Application.ShowAlertDialog();

                acEd.WriteMessage("\n关联页面设置到布局失败，程序退出");
                return;
            }

            //关联好当前布局与页面设置后，采用打印当前布局的方法，打印对应的图纸。

            string nmSpace = "MODEL";

            if (isModel == false)
            {
                nmSpace = "PAPER";
            }

            Any_PlotByAuto(nmSpace);

            Autodesk.AutoCAD.ApplicationServices.Application.SetSystemVariable("measurement", o);

        }

        #endregion

        #region 非直接打印命令区

        /// <summary>
        /// 命令 +tk 向Tk.xml文件中加入图框块的名称
        /// </summary>
        [CommandMethod("+tk")]
        public static void Add_TkName()
        {

            Document acDoc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;

            Editor acEd = acDoc.Editor;

            Entity ent;

            bool goContinue = true;

            List<string> tkNames = new List<string>();

            List<string> tkNamesInXml = new List<string>();

            tkNamesInXml.Clear();

            if (System.IO.File.Exists(xmlFilePath))
            {

                XmlTool Tool = new XmlTool(xmlFilePath);

                tkNamesInXml = Tool.Get_TkNameInfo();

            }
            else
            {
                Application.ShowAlertDialog("没有找到图框块名称记录文件Tk.xml,程序无法运行");

                return;

            }

            List<string> namesTobeAdd = new List<string>();


            while (goContinue)
            {

                PromptEntityOptions peo = new PromptEntityOptions("\n请选择要打印的图框块，不同的图框只需要选一次：");

                peo.SetRejectMessage("一次只能选择一个块");

                peo.AddAllowedClass(typeof(BlockReference), true);

                PromptEntityResult entRes = acEd.GetEntity(peo);

                DocumentLock m_DocumentLock = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.LockDocument();

                Database dbs = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.Database;


                if (entRes.Status == PromptStatus.OK)
                {
                    ObjectId obj = entRes.ObjectId;

                    using (Transaction trans = dbs.TransactionManager.StartTransaction())
                    {
                        ent = (Entity)trans.GetObject(obj, OpenMode.ForRead);

                        if (ent is BlockReference)
                        {

                            //BlockReference blkRef = (BlockReference)trans.GetObject(obj, OpenMode.ForRead);

                            BlockReference blkRef = ent as BlockReference;

                            //Application.ShowAlertDialog(blkRef.Name);

                            if (tkNamesInXml.Contains(blkRef.Name) == false && namesTobeAdd.Contains(blkRef.Name) == false)
                            {
                                namesTobeAdd.Add(blkRef.Name);
                            }

                            tkNames.Add(blkRef.Name);

                            acEd.WriteMessage("\n" + blkRef.Name);



                        }
                        trans.Commit();
                    }
                }
                else
                {
                    goContinue = false;
                }

            }


            XmlTool ToolA = new XmlTool(xmlFilePath);

            ToolA.Add_TkNamesInfo(namesTobeAdd);

        }


        /// <summary>
        /// 命令 -tk 向Tk.xml文件中加入图框块的名称
        /// </summary>
        [CommandMethod("-tk")]
        public static void Remove_TkName()
        {

            Document acDoc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;

            Editor acEd = acDoc.Editor;

            Entity ent;

            bool goContinue = true;

            List<string> tkNames = new List<string>();

            List<string> tkNamesInXml = new List<string>();

            tkNamesInXml.Clear();

            if (System.IO.File.Exists(xmlFilePath))
            {

                //XmlTool Tool = new XmlTool(xmlFilePath);

                //tkNamesInXml = Tool.Get_TkNameInfo();

            }
            else
            {
                Application.ShowAlertDialog("没有找到图框块名称记录文件Tk.xml,程序无法运行");

                return;

            }

            List<string> namesTobeRemove = new List<string>();


            while (goContinue)
            {
                PromptEntityOptions peo = new PromptEntityOptions("\n请选择要移除的图框块，不同的图框只需要选一次：");

                peo.SetRejectMessage("一次只能选择一个块");

                peo.AddAllowedClass(typeof(BlockReference), true);

                PromptEntityResult entRes = acEd.GetEntity(peo);

                DocumentLock m_DocumentLock = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.LockDocument();

                Database dbs = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.Database;


                if (entRes.Status == PromptStatus.OK)
                {
                    ObjectId obj = entRes.ObjectId;

                    using (Transaction trans = dbs.TransactionManager.StartTransaction())
                    {
                        ent = (Entity)trans.GetObject(obj, OpenMode.ForRead);

                        if (ent is BlockReference)
                        {

                            ent.Highlight();

                            //BlockReference blkRef = (BlockReference)trans.GetObject(obj, OpenMode.ForRead);

                            BlockReference blkRef = ent as BlockReference;

                            //Application.ShowAlertDialog(blkRef.Name);

                            if (tkNamesInXml.Contains(blkRef.Name) == false && namesTobeRemove.Contains(blkRef.Name) == false)
                            {
                                namesTobeRemove.Add(blkRef.Name);
                            }

                            tkNames.Add(blkRef.Name);

                            acEd.WriteMessage("\n" + blkRef.Name);



                        }
                        trans.Commit();
                    }
                }
                else
                {
                    goContinue = false;
                }

            }

            XmlTool ToolA = new XmlTool(xmlFilePath);

            ToolA.ReMove_TkNamesInfo(namesTobeRemove);

        }

        /// <summary>
        /// 命令lsset取得文件适合本空间的页面设置
        /// </summary>
        [CommandMethod("lsset")]
        public static void ListPlotSetings()
        {
            Document acDoc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;

            Database acDb = acDoc.Database;

            Editor acEd = acDoc.Editor;

            #region 获取当前布局的BlockTableRecordId，用于后面关联页面设置，同时设置isModel的值，为模型空间则设置为True，否则设置为False；

            ObjectId curLayoutId = ObjectId.Null;

            bool isModel = true;

            //获取当前空间的BlockTableRecordId，同时设置isModel的值，为模型空间则设置为True，否则设置为False；

            curLayoutId = LayoutTool.GetCurSpaceObjectId(out isModel);

            #endregion

            List<string> plotSetingsNames = new List<string>();

            List<string> plotInfoSInPlotSetings = new List<string>();

            //获取指定路径图纸中的与当前空间匹配的页面设置名称，同时输出每个匹配页面布置所对应的设置信息

            plotSetingsNames = LayoutTool.GetPlotSetingsNames(dwgFilePath, isModel, out plotInfoSInPlotSetings);

            //			System.Windows.Forms.MessageBox.Show(plotSetingsNames.Count.ToString());

            if (plotSetingsNames.Count == 0)
            {

                acEd.WriteMessage("\n没有适用于当前空间的默认页面设置，请使用<svset>命令设置默认页面布局后重试");

                return;

            }

            string aPlotSetingsName = string.Empty;

            //当只有一个的时候，在命令行输出主要页面设置信息

            //当有多个的时候，显示多个页面设置名称，及主要页面设置信息

            if (plotSetingsNames.Count == 1)
            {
                //aPlotSetingsName = plotSetingsNames[0];

                acEd.WriteMessage(plotInfoSInPlotSetings[0] + "\n");

            }
            else if (plotSetingsNames.Count > 1)
            {

                acEd.WriteMessage("\n当前空间有以下可用的页面设置：\n");

                for (int i = 0; i < plotSetingsNames.Count; i++)
                {

                    acEd.WriteMessage(plotInfoSInPlotSetings[i] + "\n");

                }

            }

        }

        /// <summary>
        /// 模型空间运行，页面设置就导出到模型空间，布局里面运行，页面设置就导出到布局空间
        /// </summary>
        [CommandMethod("svset")]
        public static void Save_PlotSetings()
        {

            Document acCurDoc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;

            Database acCurDb = acCurDoc.Database;

            Editor acCurEd = acCurDoc.Editor;

            string plotSetingsName = string.Empty;

            plotSetingsName = string.Empty;

            string curDocCurLayoutPlotSetingsName = string.Empty;

            bool curLayoutHasCurPlotSet = false;

            curLayoutHasCurPlotSet = LayoutTool.HasPlotSeting(acCurDoc, out curDocCurLayoutPlotSetingsName);

            if (curLayoutHasCurPlotSet == false)
            {

                Application.ShowAlertDialog("当前布局没有当前的页面设置，请设置好页面设置并设为当前后再运行本程序");

                return;
            }


            if (System.IO.File.Exists(dwgFilePath) == false)
            {

                acCurEd.WriteMessage("\n程序路径没有找到用来存储页面设置所需的文件，程序将自动建立该文件\n");

                using (Database tmpDb = new Database())
                {

                    tmpDb.SaveAs(dwgFilePath, DwgVersion.Current);

                }

            }

            using (Database tmpDb = new Database(false, true))
            {

                tmpDb.ReadDwgFile(dwgFilePath, System.IO.FileShare.ReadWrite, true, null);


                using (Transaction curTrans = acCurDb.TransactionManager.StartTransaction())
                {

                    DBDictionary curPlotSetingDic = curTrans.GetObject(acCurDb.PlotSettingsDictionaryId, OpenMode.ForRead) as DBDictionary;

                    //获取当前的页面设置

                    ObjectId settingsId = ObjectId.Null;

                    settingsId = curPlotSetingDic.GetAt(curDocCurLayoutPlotSetingsName);

                    PlotSettings settings = null;

                    settings = curTrans.GetObject(settingsId, OpenMode.ForRead) as PlotSettings;

                    //创建新的页面设置

                    PlotSettings newSettings = new PlotSettings(settings.ModelType);

                    newSettings.CopyFrom(settings);

                    using (Transaction tmpTrans = tmpDb.TransactionManager.StartTransaction())
                    {

                        DBDictionary tmpDict = tmpTrans.GetObject(tmpDb.PlotSettingsDictionaryId, OpenMode.ForRead) as DBDictionary;


                        //从目标db里面查找，如果有的话先删除
                        DBDictionary tmpPlotSetingsDic = tmpTrans.GetObject(tmpDb.PlotSettingsDictionaryId, OpenMode.ForRead) as DBDictionary;

                        //ObjectId tmpSettingsId = ObjectId.Null;

                        if (tmpPlotSetingsDic.Contains(plotSetingsName))
                        {
                            //DBDictionaryEntry dbEntry = dbDict.GetAt();
                            tmpPlotSetingsDic.Remove(plotSetingsName);

                        }

                        newSettings.AddToPlotSettingsDictionary(tmpDb);

                        tmpTrans.AddNewlyCreatedDBObject(newSettings, true);


                        tmpTrans.Commit();

                    }

                    curTrans.Commit();

                }

                tmpDb.SaveAs(dwgFilePath, DwgVersion.Current);

            }

            acCurEd.WriteMessage("\n当前页面设置已成功导入记录文件");

        }

        /// <summary>
        /// 模型空间运行，页面设置就导出到模型空间，布局里面运行，页面设置就导出到布局空间
        /// </summary>
        [CommandMethod("delset")]
        public static void Del_PlotSetings()
        {

            //string dwgFilePath = "";

            //string sAssemblyPath = System.Reflection.Assembly.GetExecutingAssembly().Location;

            //string shortName = System.IO.Path.GetFileName(sAssemblyPath);

            //dwgFilePath = sAssemblyPath.Replace(shortName, "DeaufltPlotSetings.dwg");


            Document acCurDoc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;

            Database acCurDb = acCurDoc.Database;

            Editor acCurEd = acCurDoc.Editor;

            #region 判断是否存在记录文件，没有的话创建一个

            if (System.IO.File.Exists(dwgFilePath) == false)
            {
                acCurEd.WriteMessage("\n程序路径没有找到用来存储页面设置所需的文件，程序将自动建立该文件\n");

                using (Database tmpDb = new Database())
                {
                    tmpDb.SaveAs(dwgFilePath, DwgVersion.Current);

                }

            }

            #endregion


            #region 获取当前布局的BlockTableRecordId，用于后面关联页面设置，同时设置isModel的值，为模型空间则设置为True，否则设置为False；

            ObjectId curLayoutId = ObjectId.Null;

            bool isModel = true;

            //获取当前空间的BlockTableRecordId，同时设置isModel的值，为模型空间则设置为True，否则设置为False；

            curLayoutId = LayoutTool.GetCurSpaceObjectId(out isModel);

            #endregion


            List<string> plotSetingsNames = new List<string>();

            List<string> plotInfoSInPlotSetings = new List<string>();

            //获取指定路径图纸中的与当前空间匹配的页面设置名称，同时输出每个匹配页面布置所对应的设置信息

            plotSetingsNames = LayoutTool.GetPlotSetingsNames(dwgFilePath, isModel, out plotInfoSInPlotSetings);

            if (plotSetingsNames.Count == 0)
            {

                acCurEd.WriteMessage("\n没有可以在本空间移除的页面设置");

                return;

            }

            string aPlotSetingsName = string.Empty;

            //当只有一个的时候，在命令行输出主要页面设置信息

            //当有多个的时候，显示多个页面设置名称，及主要页面设置信息

            if (plotSetingsNames.Count == 1)
            {

                aPlotSetingsName = plotSetingsNames[0];

            }
            else if (plotSetingsNames.Count > 1)
            {

                acCurEd.WriteMessage("\n当前空间有以下可移除的页面设置：\n");

                for (int i = 0; i < plotSetingsNames.Count; i++)
                {

                    acCurEd.WriteMessage(plotInfoSInPlotSetings[i] + "\n");

                }

            GetPageSetup:

                PromptIntegerOptions prompt_I = new PromptIntegerOptions("");

                prompt_I.AllowNone = true;

                prompt_I.AllowNegative = false;

                prompt_I.DefaultValue = 1;

                prompt_I.Message = "请输入需要移除的页面设置" + "[1-" + (plotSetingsNames.Count).ToString() + "]";

                PromptIntegerResult res_I;

                res_I = acCurEd.GetInteger(prompt_I);

                if (res_I.Status != PromptStatus.OK)
                {

                    acCurEd.WriteMessage("\n没有输入有效的页面设置选项，将放弃移除工作");

                    return;

                }

                if (res_I.Value >= 1 && res_I.Value <= plotSetingsNames.Count)
                {
                    aPlotSetingsName = plotSetingsNames[res_I.Value - 1];


                }
                else
                {
                    goto GetPageSetup;

                }

            }


            using (Database tmpDb = new Database(false, true))
            {
                tmpDb.ReadDwgFile(dwgFilePath, System.IO.FileShare.ReadWrite, true, null);

                using (Transaction tmpTrans = tmpDb.TransactionManager.StartTransaction())
                {

                    DBDictionary tmpDict = tmpTrans.GetObject(tmpDb.PlotSettingsDictionaryId, OpenMode.ForWrite) as DBDictionary;

                    //从目标db里面查找，如果有的话就删除
                    DBDictionary tmpPlotSetingsDic = tmpTrans.GetObject(tmpDb.PlotSettingsDictionaryId, OpenMode.ForRead) as DBDictionary;

                    foreach (var item in tmpPlotSetingsDic)
                    {
                        if (item.Key == aPlotSetingsName)
                        {

                            tmpPlotSetingsDic.Remove(item.Value);

                            acCurEd.WriteMessage("页面设置---" + item.Key + "----Delated！！！");

                        }

                    }

                    tmpTrans.Commit();

                }

                tmpDb.SaveAs(dwgFilePath, DwgVersion.Current);

            }

        }

        #endregion

        /// <summary>
        /// 用于单文件当前布局模型或图纸空间中的某个布局）内的框选或者自动打印
        /// </summary>
        /// <param name="nmSpace"></param>
        public static void Any_PlotByAuto(string nmSpace)
        {

            Document acDoc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;

            Database acDb = acDoc.Database;

            Editor acEd = acDoc.Editor;

            object o = Autodesk.AutoCAD.ApplicationServices.Application.GetSystemVariable("measurement");

            int svShort = Convert.ToInt16(o);

            if (svShort == 0)
            {

                acEd.WriteMessage("本程序默认使用公制单位进行打印，本图为英制图纸，将临时调整为公制进行打印，打印后恢复为英制");

                Autodesk.AutoCAD.ApplicationServices.Application.SetSystemVariable("measurement", 1);

            }

            bool hasPlotSeting = false;

            string plotSetName = string.Empty;

            string layoutName = string.Empty;


            //判断当前空间是否有当前的页面设置

            hasPlotSeting = LayoutTool.HasPlotSeting(acDoc, out plotSetName);

            if (!hasPlotSeting)
            {

                Autodesk.AutoCAD.ApplicationServices.Application.ShowAlertDialog("本空间未设置当前的页面设置，请设置后再运行本程序");

                return;
            }

            #region 设置图框块的名字blockNames

            List<string> blockNames = new List<string>();

            blockNames.Clear();

            if (System.IO.File.Exists(xmlFilePath))
            {

                XmlTool Tool = new XmlTool(xmlFilePath);

                foreach (var item in Tool.Get_TkNameInfo())
                {
                    blockNames.Add(item);
                }

            }
            else
            {

                Application.ShowAlertDialog("没有找到图框块名称记录文件Tk.xml,程序无法运行");

                return;

            }

            #endregion


            //            List<BlockReference> blocks = LayoutTool.Get_tk_BlocksBySelect(blockNames);

            List<BlockReference> blocks = LayoutTool.Get_tk_BlocksAuto(blockNames, nmSpace);

            if (blocks.Count == 0)
            {

                Autodesk.AutoCAD.ApplicationServices.Application.ShowAlertDialog("没有选择到能打印的图框块，请用命令< +tk >将要打印的图框块名称加入Tk.xml中");

                return;

            }

            //按照Z形排序图框

            List<BlockReference> tks;


            try
            {

                tks = GetGroupedAndOrderedTks(blocks);

            }
            catch (System.Exception)
            {

                tks = blocks.OrderByDescending(tk => tk.Position.Y).ThenBy(tk => tk.Position.X).ToList<BlockReference>();

                //				throw;
            }

            for (int i = 0; i < tks.Count; i++)
            {

                Extents2d window = LayoutTool.GetBlockExtent2d(tks[i]);

                //Application.ShowAlertDialog(tks[i].Name);

                string name = string.Empty;

                name = layoutName + i;

                string shortName = System.IO.Path.GetFileNameWithoutExtension(acDoc.Name) + "-";

                name = System.IO.Path.Combine(System.IO.Path.GetDirectoryName(acDoc.Name), shortName + name);

                //bool bb = LayoutTool.PlotWindowByCurPlotSetting(window, name);

                bool bb = LayoutTool.PlotWindowByCurPlotSetting(tks[i], name);

            }

            Autodesk.AutoCAD.ApplicationServices.Application.SetSystemVariable("measurement", o);

        }

        /// <summary>
        /// 用于当前空间的图纸，使用默认打印设置
        /// </summary>
        public static void Model_Plot_ALL_AUTO(int _plotSetingsIndex)
        {

            //#region 获取记录图框块名称的Tk.xml文件及页面设置所在的dwg文件路径xmlFilePath、dwgFilepath，对应autocad08及13有不同的参数

            //string dwgFilePath = "";

            ////获取图框块名称记录文件Tk.xml及页面设置所在的dwg文件路径.

            //string sAssemblyPath = System.Reflection.Assembly.GetExecutingAssembly().Location;

            //string shortName = System.IO.Path.GetFileName(sAssemblyPath);

            //dwgFilePath = sAssemblyPath.Replace(shortName, "DeaufltPlotSetings.dwg");

            //#endregion

            Document acDoc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;

            Database acDb = acDoc.Database;

            Editor acEd = acDoc.Editor;

            object o = Autodesk.AutoCAD.ApplicationServices.Application.GetSystemVariable("measurement");

            int svShort = Convert.ToInt16(o);

            if (svShort == 0)
            {

                acEd.WriteMessage("本程序默认使用公制单位进行打印，本图为英制图纸，将临时调整为公制进行打印，打印后恢复为英制");

                Autodesk.AutoCAD.ApplicationServices.Application.SetSystemVariable("measurement", 1);

            }


            #region 获取当前布局的BlockTableRecordId，用于后面关联页面设置，同时设置isModel的值，为模型空间则设置为True，否则设置为False；

            ObjectId curLayoutId = ObjectId.Null;

            bool isModel = true;

            //获取当前空间的BlockTableRecordId，同时设置isModel的值，为模型空间则设置为True，否则设置为False；

            curLayoutId = LayoutTool.GetCurSpaceObjectId(out isModel);

            #endregion

            #region 获取指定路径图纸中的与当前空间匹配的页面设置名称，导入指定名称为aPlotSetingsName的页面设置

            List<string> plotSetingsNames = new List<string>();

            List<string> plotInfoSInPlotSetings = new List<string>();

            //获取指定路径图纸中的与当前空间匹配的页面设置名称，同时输出每个匹配页面布置所对应的设置信息

            plotSetingsNames = LayoutTool.GetPlotSetingsNames(dwgFilePath, isModel, out plotInfoSInPlotSetings);


            if (plotSetingsNames.Count == 0)
            {

                acEd.WriteMessage("\n没有适用于当前空间的默认页面设置，请使用<svset>命令设置默认页面布局后重试");

                return;

            }

            string aPlotSetingsName = string.Empty;

            //当只有一个的时候，在命令行输出主要页面设置信息

            //当有多个的时候，显示多个页面设置名称，及主要页面设置信息

            if (plotSetingsNames.Count == 1)
            {
                aPlotSetingsName = plotSetingsNames[0];

            }
            else if (plotSetingsNames.Count > 1)
            {

                if (_plotSetingsIndex >= 1 && _plotSetingsIndex <= plotSetingsNames.Count)
                {

                    aPlotSetingsName = plotSetingsNames[_plotSetingsIndex - 1];

                }

            }


            bool getInPlotSetings = false;

            if (aPlotSetingsName == string.Empty)
            {
                return;

            }

            getInPlotSetings = LayoutTool.GetInAtPlotSetings(dwgFilePath, aPlotSetingsName, isModel);

            //如果导入不成功，说明相关原因

            if (getInPlotSetings == false)
            {
                acEd.WriteMessage("没有找到所需的页面设置名称,程序放弃打印");

                return;
            }

            #endregion


            //导入页面设置成功,关联打印设置

            if ( LayoutTool.AssignPage_SetupToLayout(curLayoutId, aPlotSetingsName)==false)
            {
                Application.ShowAlertDialog("");

                acEd.WriteMessage("\n关联页面设置到布局失败，程序退出");
                return;
            }
           

            //关联好当前布局与页面设置后，采用打印当前布局的方法，打印对应的图纸。

            //			string nmspace="MODEL";
            //			
            //			if (isModel==false) {
            //				
            //				nmspace="PAPER";
            //				
            //			}

            Any_PlotByAuto("MODEL");

            //			Any_PlotBySelect();

            Autodesk.AutoCAD.ApplicationServices.Application.SetSystemVariable("measurement", o);

            //最后进行批量打印

            //将页面名称导入本图纸

            //设置为当前页面设置

            //批量打印所选择的图框

        }

        //public static List<BlockReference> GetGroupedAndOrderedTks(List<BlockReference> tks)
        //{
        //    List<BlockReference> tksOrdered = new List<BlockReference>();

        //    //排序规则
        //    //如果图框没有图纸编号信息那就直接按照图框位置X升序，Y降序排列图框
        //    //如果图框有图纸编号信息，那就先按照图纸编号将图框块分组，分组按照图框块中的图名进行排序
        //    //按图名分组后，再判断是否有页码数据，如果有页码则按照页码升序排列图框

        //    string tmpStr = GetTagValue("图纸编号", tks[0]);


        //    if (tmpStr == string.Empty)
        //    {

        //        tksOrdered = tks.OrderBy(tk => tk.Position.X).ThenByDescending(tk => tk.Position.Y).ToList();

        //    }
        //    else
        //    {

        //        var qurry_r = from r in tks
        //                      group r by GetTagValue("图纸编号", r) into rrGroup
        //                      orderby GetTagValue("图纸编号", rrGroup.ElementAt(0))
        //                      select rrGroup;

        //        //第一组中第一个块

        //        BlockReference Block_tmp =(((qurry_r.ToList())[0]).ToList())[0] as BlockReference;

        //        //判断有没有页码信息

        //        bool bb = GetPageNo("第页", Block_tmp) == 0;

        //        if (bb)
        //        {
        //            //没有页码信息时,按照X升序，Y降序排序

        //            foreach (var item in qurry_r)
        //            {

        //                var orderG = from r in item
        //                             orderby r.Position.X,r.Position.Y descending
        //                             select r;

        //                foreach (var item_tmp in orderG.ToList())
        //                {

        //                    BlockReference tmpBlock = item_tmp as BlockReference;

        //                    if (tmpBlock != null)
        //                    {

        //                        tksOrdered.Add(tmpBlock);
        //                    }

        //                }

        //            }

        //        }
        //        else
        //        {
        //            //有页码信息的时候，优先采用页码排序，页码相同的时候按照X升序，Y降序排序

        //            foreach (var item in qurry_r)
        //            {

        //                var orderG = from r in item
        //                             //orderby GetPageNo("第页", r)
        //                             orderby GetPageNo("第页", r), r.Position.X, r.Position.Y descending
        //                             select r;

        //                foreach (var item_tmp in orderG.ToList())
        //                {

        //                    BlockReference tmpBlock = item_tmp as BlockReference;

        //                    if (tmpBlock != null)
        //                    {

        //                        tksOrdered.Add(tmpBlock);
        //                    }

        //                }

        //            }

        //        }

        //    }


        //    return tksOrdered;


        //}

        //public static List<BlockReference> GetGroupedAndOrderedTks(List<BlockReference> tks)
        //{
        //    List<BlockReference> tksOrdered = new List<BlockReference>();

        //    //排序规则
        //    //如果图框没有图纸编号信息那就直接按照图框位置X升序，Y降序排列图框
        //    //如果图框有图纸编号信息，那就先按照图纸编号将图框块分组，分组按照图框块中的图名进行排序
        //    //按图名分组后，再判断是否有页码数据，如果有页码则按照页码升序排列图框

        //    //没有取得有效的图纸编号，或者没有图纸编号，那就会全部分到一个组中，如果有有效的图纸编号，就会分成几个组

        //    var qurry_r = from r in tks
        //                  group r by GetTagValue("图纸编号", r) into rrGroup
        //                  orderby GetTagValue("图纸编号", rrGroup.ElementAt(0))
        //                  select rrGroup;



        //    foreach (var item in qurry_r)
        //    {

        //        //先按照页码排序，如果页码一致，再按照X增大排序，如果X还一致，那就按照Y降序排列

        //        var orderG = from r in item
        //                     orderby GetPageNo("第页", r), r.Position.X, r.Position.Y descending
        //                     select r;


        //        foreach (var item_tmp in orderG.ToList())
        //        {

        //            BlockReference tmpBlock = item_tmp as BlockReference;

        //            if (tmpBlock != null)
        //            {

        //                tksOrdered.Add(tmpBlock);
        //            }

        //        }

        //    }

        //    return tksOrdered;


        //}

        public static List<BlockReference> GetGroupedAndOrderedTks(List<BlockReference> tks)
        {
            List<BlockReference> tksOrdered = new List<BlockReference>();

            //排序规则
            //如果图框没有图纸编号信息那就直接按照图框位置X升序，Y降序排列图框
            //如果图框有图纸编号信息，那就先按照图纸编号将图框块分组，分组按照图框块中的图名进行排序
            //按图名分组后，再判断是否有页码数据，如果有页码则按照页码升序排列图框

            //没有取得有效的图纸编号，或者没有图纸编号，那就会全部分到一个组中，如果有有效的图纸编号，就会分成几个组

            //var qurry_r = from r in tks
            //              group r by GetTagValue("图纸编号", r) into rrGroup
            //              orderby GetTagValue("图纸编号", rrGroup.ElementAt(0))
            //              select rrGroup;



            //foreach (var item in qurry_r)
            //{

            //    //先按照页码排序，如果页码一致，再按照X增大排序，如果X还一致，那就按照Y降序排列

            //    var orderG = from r in item
            //                 orderby GetPageNo("第页", r), r.Position.X, r.Position.Y descending
            //                 select r;


            //    foreach (var item_tmp in orderG.ToList())
            //    {

            //        BlockReference tmpBlock = item_tmp as BlockReference;

            //        if (tmpBlock != null)
            //        {

            //            tksOrdered.Add(tmpBlock);
            //        }

            //    }

            //}


            var orderG = from r in tks
                         orderby GetTagValue("工程名称", r), GetTagValue("项目名称", r), GetTagValue("图纸编号", r), GetPageNo("第页", r), r.Position.Y descending,r.Position.X
                         select r;


            foreach (var item_tmp in orderG.ToList())
            {

                BlockReference tmpBlock = item_tmp as BlockReference;

                if (tmpBlock != null)
                {

                    tksOrdered.Add(tmpBlock);
                }

            }

            return tksOrdered;


        }

        public static int GetPageNo(string tag_str, BlockReference block_Ref)
        {

            int pageNoValue = 0;


            Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;

            Editor acEd = doc.Editor;


            using (Transaction acTrans = doc.Database.TransactionManager.StartTransaction())
            {

                foreach (ObjectId att_id in block_Ref.AttributeCollection)
                {

                    AttributeReference attRef = acTrans.GetObject(att_id, OpenMode.ForRead, false) as AttributeReference;

                    if (attRef.Tag.ToString() == tag_str)
                    {


                        int pageNo = 1;

                        bool b = false;

                        b = int.TryParse(attRef.TextString, out pageNo);

                        if (b == true)
                        {

                            pageNoValue = pageNo;


                        }

                    }

                }

            }



            return pageNoValue;




        }

        public static string GetTagValue(string tag_str, BlockReference block_Ref)
        {

            string tagValue = string.Empty;

            Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;

            Editor acEd = doc.Editor;

            using (Transaction acTrans = doc.Database.TransactionManager.StartTransaction())
            {

                // 检查以确定返回的 SelectedObject 对象是有效的     Check to make sure a valid SelectedObject object was returned

                // 以写的方式打开选择的对象   Open the selected object for write

                foreach (ObjectId att_id in block_Ref.AttributeCollection)
                {

                    AttributeReference attRef = acTrans.GetObject(att_id, OpenMode.ForRead, false) as AttributeReference;

                    if (attRef.Tag.ToString() == tag_str)
                    {

                        tagValue = attRef.TextString;

                    }

                }



                acTrans.Commit();
            }

            return tagValue;
        }

        void XG_SXZ(string tag_str, string val_str, string block_name)
        {

            Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;

            Editor acEd = doc.Editor;

            TypedValue[] filList = new TypedValue[1];

            filList[0] = new TypedValue((int)DxfCode.BlockName, block_name);

            SelectionFilter sf = new SelectionFilter(filList);

            PromptSelectionResult psr = acEd.SelectAll(sf);

            if (psr.Status == PromptStatus.OK)
            {

                SelectionSet SS = psr.Value;

                ObjectId[] idArray = SS.GetObjectIds();

                for (int i = 0; i < idArray.Count(); i++)
                {
                    using (Transaction acTrans = doc.Database.TransactionManager.StartTransaction())
                    {
                        // 检查以确定返回的 SelectedObject 对象是有效的     Check to make sure a valid SelectedObject object was returned

                        // 以写的方式打开选择的对象   Open the selected object for write

                        Entity A_ent = acTrans.GetObject(idArray[i], OpenMode.ForWrite) as Entity;


                        if (A_ent is BlockReference)
                        {
                            BlockReference block_Ref = A_ent as BlockReference;

                            block_Ref.Highlight();

                            foreach (ObjectId att_id in block_Ref.AttributeCollection)
                            {
                                AttributeReference attRef = acTrans.GetObject(att_id, OpenMode.ForWrite, false) as AttributeReference;

                                if (attRef.Tag.ToString() == tag_str)
                                {

                                    attRef.TextString = val_str;

                                }

                            }

                        }

                        acTrans.Commit();
                    }

                }

            }

        }
    }

}
